crypto = require('crypto')
request = require('request')
md5 = (input) ->
	hash = crypto.createHash('md5')
	return hash.update(input).digest("hex")

PREFIX = 'https://mp.weixin.qq.com/cgi-bin/'

Pusher =	(username, password) ->
	this.username = username
	this.password = password
	this.cookie = null
	this.token = ''
	@

Pusher.prototype.login =	(callback) ->
	that = this
	submitUrl = PREFIX + 'login?lang=zh_CN'

	data = {
		username: this.username
		pwd: md5(this.password)
		imgcode:''
		f: 'json'
	}

	options = {
		url:submitUrl
		form : data
		method : 'POST'
		json : true
		cookie: true
		headers: {
			'Referer': PREFIX + 'loginpage?t=wxm2-login&lang=zh_CN'
			'User-Agent': 'Mozilla/5.0 (Macintosh Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'
		}
	}

	request options,	(err, res, body) ->
		if err
			return callback(err)

		fields = res.cookie
		fields = res.headers['set-cookie']
		fields = if Array.isArray(fields) then fields else [fields]
		that.jar = request.jar()
		cookies = fields.map	(item)->
			cookie = request.cookie item.replace('Path=/ Secure HttpOnly', '').replace('', '').trim()
			that.jar.add cookie 
		token = body.ErrMsg.match(/token=(\d*)/)
		that.token = token[1]
		callback(null)

Pusher.prototype.send = (fakeId, content, callback)->
	that = this;
	that._send fakeId, content, (err, body)->
		if err
			that.login ()->
				that._send fakeId, content, callback
		else
			callback null, body

Pusher.prototype._send =	(fakeId, content, callback)->
	token = this.token
	data = 
		'tofakeid': fakeId,
		'type': 1,
		'content': content,
		'error': 'false',
		'imgcode': '',
		'token': token,
		'ajax': 1

	options = 
		headers: 
			'Referer': PREFIX + 'singlemsgpage?token=' + token + '&fromfakeid=' + fakeId + '&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN'
			'User-Agent': 'Mozilla/5.0 (Macintosh Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'
			'X-Requested-With':'XMLHttpRequest'
			'Host':'mp.weixin.qq.com'
			'Origin':'https://mp.weixin.qq.com'
		method: 'POST'
		json: true
		form: data
		jar: this.jar
		url: PREFIX + 'singlesend?t=ajax-response&lang=zh_CN'
	request options,	(err, res, body)->
		if (err) 
			return callback(err)
		if (body.ret isnt '0')
			e = new Error(body.msg)
			e.name = 'WechatPushError'
			return callback(e)

		callback(err, body)

Pusher.prototype.getAvatar =	(fakeId)->
	return PREFIX + 'getheadimg?token=' + this.token + '&fakeid=' + fakeId


Pusher.prototype.getFans = (page, cb)->
	that = this
	that.login (err)->
		return cb err if err
		request.get "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=1000&pageidx=#{page}&type=0&groupid=0&token=#{that.token}&lang=zh_CN",(err, res, body)->
			return cb err if err
			body.replace /"contacts":(.*?)}\).contacts/g, ($0,$1)->
				cb err,JSON.parse($1)	

module.exports = new Pusher('2920330166@qq.com','dutuwen.com')

# if require.main is module
# 	pusher = new Pusher('cupitrh@gmail.com','321321')
# 	pusher.login ()->
# 		pusher.getFans 0 , (err, body)->
# 			body.replace /"contacts":(.*?)}\).contacts/g, ($0,$1)->
# 				JSON.parse $1	
